package com.googlecode.afx.view.behavior;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.scene.Node;

/**
 * Adapter class that converts a change event into a view-state change event.
 * 
 * @author Martin
 *
 */
@SuppressWarnings("rawtypes")
public class ViewStateListenerAdapter implements ViewStateListener, ChangeListener, ListChangeListener {

	private Node rootNode;
	
	private Node attachedNode;
	
	private ViewStateListener listener;
	
	public ViewStateListenerAdapter(Node rootNode, Node attachedNode, ViewStateListener listener) {
		this.rootNode = rootNode;
		this.attachedNode = attachedNode;
		this.listener = listener;
	}

	/**
	 * Event handler of <tt>ViewStateListener</tt>. Forward event to the handling listener.
	 */
	@Override
	public void onStateChange(Node rootNode, ChangeDetails changeDetails) {
		this.listener.onStateChange(rootNode, changeDetails);
	}

	/**
	 * Event-handler of <tt>ChangeListener</tt>. Delegates to <tt>ViewStateListener</tt> event handler.
	 */
	@Override
	public void changed(ObservableValue observable, Object oldValue, Object newValue) {
		ChangeDetails changeDetails = new ChangeDetails();
		changeDetails.setChangedNode(attachedNode);
		changeDetails.setChangeType(ChangeDetails.ChangeType.FIELD);
		changeDetails.setOldValue(oldValue);
		changeDetails.setNewValue(newValue);
		this.onStateChange(rootNode, changeDetails);
	}

	/**
	 * Event handler of <tt>ListChangeListener</tt>. Delegates to <tt>ViewStateListener</tt> event handler.
	 */
	@Override
	public void onChanged(Change c) {
		ChangeDetails changeDetails = new ChangeDetails();
		changeDetails.setChangedNode(attachedNode);
		changeDetails.setChangeType(ChangeDetails.ChangeType.LIST);
		changeDetails.setListChange(c);
		this.onStateChange(rootNode, changeDetails);
	}

}
